<?php
  class blog_model{
    var $path;
    function __construct($data_dir){
      $this->data_dir = $data_dir;
    }
    
    function get_post_list($dir = '', $page = 0, $display = 10) {
      $posts = array();
      foreach (filemanager::treefilelist($this->data_dir . $dir) as $file) {
        $pathinfo = pathinfo($this->data_dir . $dir. $file);
        if ($pathinfo['extension'] == 'blog') {
          $posts[] = $file;
        }
        if (!file_exists(filemanager::ext_replace('blog','xml',$this->data_dir .$dir. $file))) {
          $this->generate_info($this->data_dir .$dir. $file);
        }
      }
      return array_slice($posts,($page-1)*$display,$display);
    }
    
    function sort_posts($file){
      
    }
    
    function generate_info ($file) {
      $blog = $this->parse_blog ($file);
      $xml = 
'<?xml version="1.0" encoding="UTF-8" ?>
<postinfo>
  <title>'.$blog['title'].'</title>
  <latlng>0,0</latlng>
  <posttime>'.date('Y-m-d H:i:s', filectime($file)).'</posttime>
  <modified />
  <comments />
</postinfo>';
      return file_put_contents(filemanager::ext_replace('blog','xml',$file), $xml);
    }
    
    function parse_blog($file){
      $fd = fopen($file, "r");
      $content = '';
      while ($line = fgets($fd, 4096)) {
        if (!isset($title)) {
          $title = str_replace(array("\n","\r"),'',$line);
        } else {
          $content .= $line;
        }
      }
      fclose($fd);
      return array('title' => $title, 'content' => $content);
    }
    
    function find($file){
      if (!file_exists(filemanager::ext_replace('blog','xml',$file))) {
        $this->generate_info($file);
      }
      $blog = $this->parse_blog($file);
      return array(
        'title' => $blog['title'],
        'content' => $blog['content']
      );
    }
  }